package com.zhang.study.chapter01;

import java.util.Arrays;

import static com.zhang.util.RandomArrayUtil.generateRandomSortedArray;

/**
 * @author zhang
 * @date 2023/11/21 14:01
 * @description 二分查找 查找数组中是否存在一个数
 */
public class Code04_BSExist {

    /**
     * 二分查找
     *
     * @param sortedArr 有序数组
     * @param target    目标
     * @return true 存在 false 不存在
     */
    public static boolean binarySearch(int[] sortedArr, int target) {
        if (sortedArr == null || sortedArr.length == 0) {
            return false;
        }
        int left = 0;
        int right = sortedArr.length - 1;
        while (left <= right) {
            // 可能出现int溢出
            // int mid = (left + right) / 2;
            int mid = left + ((right - left) >> 1); // 右移运算符来代替除法运算符
            if (sortedArr[mid] == target) {
                return true;
            } else if (sortedArr[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int maxSize = 100;
        int maxValue = 100;
        int testTime = 50000;
        for (int i = 0; i < testTime; i++) {
            int[] sortedArray = generateRandomSortedArray(maxSize, maxValue);
            int value = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
            boolean result = binarySearch(sortedArray, value);
            int index = Arrays.binarySearch(sortedArray, value);
            if (result != (index >= 0)) {
                System.out.println("binarySearch error!");
            }
        }
        System.out.println("binarySearch is ok!");
    }

}
